package com.maori.languageapp.discover.story;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import com.maori.languageapp.R;
import com.maori.languageapp.consts.ImageLoader;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.media.AudioManager;
import android.os.AsyncTask;

public class Maori_Discover_Story_Adapter extends BaseAdapter {
	// Declare Variables
	Context context;
	LayoutInflater inflater;
	ArrayList<HashMap<String, String>> data;
	ImageLoader imageLoader;
	String DisplayImageSource;
	private LayoutInflater mInflater;
	HashMap<String, String> resultp = new HashMap<String, String>();
	String BookMarkState,UserNodeLikedState,node_dif_audio_url;
	private MediaPlayer mediaPlayer;
	HttpParams httpParameters = new BasicHttpParams();
	int timeoutConnection = 5000;
	JSONArray jsonarray;
	InputStream is = null;
	StringBuilder sb = null;
	String result;
	String NID,USERID;

	public Maori_Discover_Story_Adapter(Context context,
			ArrayList<HashMap<String, String>> arraylist) {
		this.context = context;
		data = arraylist;
		imageLoader = new ImageLoader(context);
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		// Declare Variables
		final ViewHolder holder;
		// Declare Variables
		if (convertView == null) {
			convertView = mInflater.inflate(
					R.layout.maori_discover_main_list_raw, null);
			holder = new ViewHolder();
			holder.maori_title = (TextView) convertView
					.findViewById(R.id.discover_maori_title);
			holder.english_title = (TextView) convertView
					.findViewById(R.id.discover_english_title);
			holder.Synonims = (Button) convertView
					.findViewById(R.id.textrawtxta);
			holder.Audios = (Button) convertView.findViewById(R.id.textrawtxtb);
			holder.Images = (Button) convertView.findViewById(R.id.textrawtxtc);
			holder.Videos = (Button) convertView.findViewById(R.id.textrawtxtd);
			holder.Likes = (Button) convertView.findViewById(R.id.textrawtxte);
			holder.discover_bookmark = (Button) convertView
					.findViewById(R.id.discover_bookmark);
			holder.playdefaultaudio = (Button) convertView
					.findViewById(R.id.playdefaultaudio);
			// Locate the ImageView in listview_item.xml
			holder.flag = (ImageView) convertView
					.findViewById(R.id.mem_discover_img);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		resultp = data.get(position);

		holder.maori_title.setText(resultp.get(Maori_Discover_Story.getWord()));
		holder.english_title
				.setText(resultp.get(Maori_Discover_Story.getWordb()));

		// Print Bottom Raw Count details
		holder.Synonims.setText(resultp.get(Maori_Discover_Story
				.getTotalsSynonim()));
		holder.Audios
				.setText(resultp.get(Maori_Discover_Story.getTotalAudios()));
		holder.Images
				.setText(resultp.get(Maori_Discover_Story.getTotalImages()));
		holder.Videos
				.setText(resultp.get(Maori_Discover_Story.getTotalVideos()));
		holder.Likes.setText(resultp.get(Maori_Discover_Story.getTotalsLikes()));
		holder.playdefaultaudio.setText(resultp.get(Maori_Discover_Story
				.getNode_dif_audio_url()));

		String NodeMainImage = resultp.get(Maori_Discover_Story.getM_Source());
		if (NodeMainImage.equals("404")) {
			DisplayImageSource = "http://langapp.mirzabros.com/images/placeholder.png";
		} else {
			DisplayImageSource = resultp.get(Maori_Discover_Story.getM_Source());
		}

		imageLoader.DisplayImage(DisplayImageSource, holder.flag);

		UserNodeLikedState = resultp.get(Maori_Discover_Story.getUserLikedForNode());
		BookMarkState = resultp
				.get(Maori_Discover_Story.getUserNodeBookMarked());
		node_dif_audio_url = resultp.get(Maori_Discover_Story
				.getNode_dif_audio_url());
		Log.v("TAG", "UUU LIKE : " + UserNodeLikedState);
		if(!UserNodeLikedState.equals("0")){
			holder.Likes.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_like_active_raw_count, 0);
		}

		// Check book mark state
		if (BookMarkState.equals("0")) {
			holder.discover_bookmark
					.setBackgroundResource(R.drawable.ic_bm_inactive);
			//new UploadBookMarkDetails().execute();

		}

		// Check default audio available
		if (!node_dif_audio_url.equals("202")) {
			holder.playdefaultaudio.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_play_h, 0);
			holder.playdefaultaudio.setEnabled(true);
			// playdefaultaudio.setCompoundDrawablesWithIntrinsicBounds(left,
			// top, right, bottom)
		}

		holder.discover_bookmark.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				resultp = data.get(position);
				NID = resultp.get(Maori_Discover_Story.getNID());
				USERID = resultp.get(Maori_Discover_Story.getMAINUID());
				BookMarkState = resultp.get(Maori_Discover_Story
						.getUserNodeBookMarked());
				Log.v("TAG", "NID*******: " + NID);
				Log.v("TAG", "USERID****: " + USERID);
				Log.v("TAG", "BookMarkState******: " + BookMarkState);
				
				
				if (BookMarkState.equals("0")) {
					BookMarkState = "1";
					resultp.put("UserNodeBookMarked", BookMarkState);
					holder.discover_bookmark
							.setBackgroundResource(R.drawable.ic_bookmark_h);
				} else {
					BookMarkState = "0";
					resultp.put("UserNodeBookMarked", BookMarkState);
					holder.discover_bookmark
							.setBackgroundResource(R.drawable.ic_bm_inactive);
				}
				
				new UploadBookMarkDetails().execute();
			}
		});

		// Capture button clicks on ListView items
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Get the position from the results
				HashMap<String, String> resultp = new HashMap<String, String>();
				resultp = data.get(position);
				// Send single item click data to SingleItemView Class
				Intent intent = new Intent(context,
						Maori_Discover_Story_Details.class);
				intent.putExtra("word",
						resultp.get(Maori_Discover_Story.getWord()));
				intent.putExtra("maori",
						resultp.get(Maori_Discover_Story.getWordb()));
				intent.putExtra("nid",
						resultp.get(Maori_Discover_Story.getNID()));
				intent.putExtra("Source",
						resultp.get(Maori_Discover_Story.getM_Source()));
				intent.putExtra("MID",
						resultp.get(Maori_Discover_Story.getMID()));
				intent.putExtra("first_name",
						resultp.get(Maori_Discover_Story.getFirst_name()));
				intent.putExtra("last_name",
						resultp.get(Maori_Discover_Story.getLast_name()));
				intent.putExtra("tribe",
						resultp.get(Maori_Discover_Story.getTribe()));
				intent.putExtra("userimage",
						resultp.get(Maori_Discover_Story.getUserimage()));
				intent.putExtra("TotalsSynonim",
						resultp.get(Maori_Discover_Story.getTotalsSynonim()));
				intent.putExtra("TotalAudios",
						resultp.get(Maori_Discover_Story.getTotalAudios()));
				intent.putExtra("TotalImages",
						resultp.get(Maori_Discover_Story.getTotalImages()));
				intent.putExtra("TotalVideos",
						resultp.get(Maori_Discover_Story.getTotalVideos()));
				intent.putExtra("TotalsLikes",
						resultp.get(Maori_Discover_Story.getTotalsLikes()));
				context.startActivity(intent);
				((Maori_Discover_Story)context).finish();

			}
		});

		return convertView;
	}

	/**************** Uploading Book Mark details ***************************/
	private class UploadBookMarkDetails extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				JSONObject json = new JSONObject();

				httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/saveNodeBookMark.php");
				// Selected Type ID / content_type_id
				json.put("record1", NID);
				// Selected UID / added_by
				json.put("record2", USERID);

				json.put("record3", "0");
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			
		}
	}

	static class ViewHolder {
		TextView maori_title;
		TextView english_title;
		Button Synonims;
		Button Audios;
		Button Images;
		Button Videos;
		Button Likes;
		Button discover_bookmark;
		Button playdefaultaudio;
		ImageView flag;
	}
}
